/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUIChamadosIncluir.java
 *
 * Created on 01/06/2011, 00:23:24
 */

package gui;

import dao.DAOCategoria;
import dao.DAOChamadoCab;
import dao.DAOChamadoDet;
import dao.DAOCliente;
import dao.DAOOperador;
import dao.DAOUsuario;
import dao.ResultSetComboBox;
import javax.swing.JOptionPane;
import model.ChamadoCab;
import model.ChamadoDet;
import model.KeyValue;

/**
 * Interface para inclusão de novos chamados
 * @author Janio Luiz Antunes
 * @author Marcel Vinicius Kohls
 * @see http://code.google.com/p/sysdesk-java/
 *
 */
public class GUIChamadosIncluir extends javax.swing.JFrame {

    private DAOCliente daoCliente = new DAOCliente();
    private DAOUsuario daoUsuario = new DAOUsuario();
    private DAOCategoria daoCategoria = new DAOCategoria();
    private DAOOperador daoOperador = new DAOOperador();
    private DAOChamadoCab daoChamadoCab = new DAOChamadoCab();
    private DAOChamadoDet daoChamadoDet = new DAOChamadoDet();

    private int operadorAtual;

    ChamadoCab chamadoCab = new ChamadoCab();
    ChamadoDet chamadoDet = new ChamadoDet();

    /** Creates new form GUIChamadosIncluir */
    public GUIChamadosIncluir() {
        initComponents();
        initDados();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jcbClientes = new javax.swing.JComboBox();
        jcbUsuarios = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtpDescricao = new javax.swing.JTextPane();
        jcbCategorias = new javax.swing.JComboBox();
        jcbOperadorDestino = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jcbCriticidade = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jbtCancelar = new javax.swing.JButton();
        jbtConfirmar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Incluir chamado");

        jcbClientes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jcbClientes.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbClientesItemStateChanged(evt);
            }
        });

        jcbUsuarios.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jScrollPane1.setViewportView(jtpDescricao);

        jcbCategorias.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jcbCategorias.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbCategoriasItemStateChanged(evt);
            }
        });

        jcbOperadorDestino.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel1.setText("Cliente:");

        jLabel2.setText("Usuário:");

        jLabel3.setText("Descrição:");

        jLabel4.setText("Categoria:");

        jLabel5.setText("Operador destinado:");

        jcbCriticidade.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Baixa", "Normal", "Alta" }));

        jLabel6.setText("Criticidade:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                    .addComponent(jcbUsuarios, 0, 292, Short.MAX_VALUE)
                    .addComponent(jcbClientes, 0, 292, Short.MAX_VALUE)
                    .addComponent(jcbCategorias, 0, 292, Short.MAX_VALUE)
                    .addComponent(jcbOperadorDestino, 0, 292, Short.MAX_VALUE)
                    .addComponent(jcbCriticidade, 0, 292, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jcbCategorias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jcbOperadorDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5)))
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbCriticidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        jbtCancelar.setText("Cancelar");
        jbtCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCancelarActionPerformed(evt);
            }
        });

        jbtConfirmar.setText("Confirmar");
        jbtConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtConfirmarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jbtCancelar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtConfirmar))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(7, 7, 7)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtConfirmar)
                    .addComponent(jbtCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Define o codigo do operador para a instancia desta GUI
     * @param pCodOperador
     */
    public void setCodOperador(int pCodOperador){
        operadorAtual = pCodOperador;
    }

    /**
     * Inicializa dados desta tela, preenchendo os combos e zerando os campos necessários
     */
    private void initDados(){
        try {
            jcbClientes.setModel(new ResultSetComboBox(daoCliente.getListaClientes(daoCliente.SEL_ATIVOS, " "), "cli_nome", "cli_codigo", 0).getModel());
            jcbUsuarios.removeAllItems();
            jcbCategorias.setModel(new ResultSetComboBox(daoCategoria.getListaCategorias(""), "cat_descricao", "cat_codigo", 0).getModel());
            jcbOperadorDestino.removeAllItems();
            
            jtpDescricao.setText("");
        } catch (Exception e) {
            System.out.println("initDados:erro: "+e.getMessage());
        }
    }

    /**
     *
     * Fecha esta janela
     */
    private void jbtCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_jbtCancelarActionPerformed

    /**
     *
     * Carrega a lista de usuários do cliente selecionado
     */
    private void jcbClientesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbClientesItemStateChanged
        if (jcbClientes.getSelectedIndex() != -1) {
            try {
                jcbUsuarios.setModel(new ResultSetComboBox(daoUsuario.getListaUsuarios((Integer)(((KeyValue) jcbClientes.getSelectedItem()).getValue()),""), "usu_nome", "usu_codigo", 0).getModel());
            } catch (Exception e) {

            }
        }
    }//GEN-LAST:event_jcbClientesItemStateChanged

    /**
     *
     * Carrega a lista de operadores conforme a categoria selecioanda
     */
    private void jcbCategoriasItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbCategoriasItemStateChanged
        if (jcbCategorias.getSelectedIndex() != -1) {
            try {
                jcbOperadorDestino.setModel(new ResultSetComboBox(daoOperador.getListaOperadoresPorCategoria((Integer)(((KeyValue) jcbCategorias.getSelectedItem()).getValue())), "ope_nome", "ope_codigo", 0).getModel());
            } catch (Exception e) {
                
            }
        }
    }//GEN-LAST:event_jcbCategoriasItemStateChanged

    /**
     *
     * Salva o chamado
     */
    private void jbtConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtConfirmarActionPerformed
        int codCabecalho = 0;

        try {
            // adiciona cabecalho
            chamadoCab.setCodigo(0);
            chamadoCab.setCodCategoria((Integer)(((KeyValue) jcbCategorias.getSelectedItem()).getValue()));
            chamadoCab.setCodCliente((Integer)(((KeyValue) jcbClientes.getSelectedItem()).getValue()));
            chamadoCab.setCodUsuario((Integer)(((KeyValue) jcbUsuarios.getSelectedItem()).getValue()));
            chamadoCab.setCodOperador(operadorAtual);
            chamadoCab.setIndiceSituacao(chamadoCab.SIT_ABERTO);
            chamadoCab.setIndiceCriticidade(jcbCriticidade.getSelectedIndex());

            codCabecalho = daoChamadoCab.salvar(chamadoCab);

            // adiciona primeiro registro deste chamado
            chamadoDet.setCodOperador((Integer)(((KeyValue) jcbOperadorDestino.getSelectedItem()).getValue()));
            chamadoDet.setDescricao(jtpDescricao.getText());

            daoChamadoDet.salvar(chamadoDet, codCabecalho);
            
            // fecha tudo
            JOptionPane.showMessageDialog(null, "Chamado aberto com sucesso! \n Protocolo número: " + codCabecalho);
            this.dispose();
        } catch (Exception e) {
            System.out.println("GUIChamados:Salvar:erro: "+e.getMessage());
            JOptionPane.showMessageDialog(null, "Erro ao salvar chamado. \n"+e.getMessage());
        }

    }//GEN-LAST:event_jbtConfirmarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUIChamadosIncluir().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton jbtCancelar;
    private javax.swing.JButton jbtConfirmar;
    private javax.swing.JComboBox jcbCategorias;
    private javax.swing.JComboBox jcbClientes;
    private javax.swing.JComboBox jcbCriticidade;
    private javax.swing.JComboBox jcbOperadorDestino;
    private javax.swing.JComboBox jcbUsuarios;
    private javax.swing.JTextPane jtpDescricao;
    // End of variables declaration//GEN-END:variables

}
